#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTML模板邮件发送示例

展示如何使用模板系统发送邮件
"""

from report_mailer.queue import MailQueue
from report_mailer.template import TemplateRenderer, render_table_rows, render_list_items
from datetime import datetime


def example1_simple_template():
    """示例1: 简单的欢迎邮件"""

    print("\n" + "=" * 60)
    print("示例1: 使用welcome.html模板发送欢迎邮件")
    print("=" * 60)

    # 1. 准备模板变量
    context = {
        "username": "张三",
        "register_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "activation_link": "https://example.com/activate?token=abc123"
    }

    # 2. 渲染模板
    renderer = TemplateRenderer(template_dir="../templates")
    html_content = renderer.render("welcome.html", context)

    print("\n[渲染的HTML预览]")
    print(html_content[:200] + "...")

    # 3. 入队发送
    queue = MailQueue("mailer.sqlite3")
    payload = {
        "subject": "欢迎注册 - 请激活您的账号",
        "to": ["user@example.com"],
        "body_html": html_content,
        "body_text": f"欢迎 {context['username']}, 请访问 {context['activation_link']} 激活账号"
    }

    queue_id = queue.enqueue(payload)
    print(f"\n[OK] 邮件已入队, ID: {queue_id}")


def example2_complex_report():
    """示例2: 复杂的数据报表邮件"""

    print("\n" + "=" * 60)
    print("示例2: 使用report.html模板发送周报")
    print("=" * 60)

    # 1. 准备数据
    table_data = [
        {"date": "2025-10-15", "visits": "1,234", "rate": "5.2%", "revenue": "¥12,340"},
        {"date": "2025-10-16", "visits": "1,456", "rate": "6.1%", "revenue": "¥15,678"},
        {"date": "2025-10-17", "visits": "1,678", "rate": "7.3%", "revenue": "¥18,901"},
        {"date": "2025-10-18", "visits": "1,890", "rate": "8.2%", "revenue": "¥22,345"},
        {"date": "2025-10-19", "visits": "2,012", "rate": "9.1%", "revenue": "¥25,678"},
    ]

    highlights = [
        "用户增长率达到历史新高 25%",
        "转化率环比提升 15%",
        "新功能上线,用户满意度 95%",
        "完成季度目标 110%"
    ]

    # 2. 渲染表格和列表
    table_rows_html = render_table_rows(table_data, ["date", "visits", "rate", "revenue"])
    highlights_html = render_list_items(highlights)

    # 3. 准备模板变量
    context = {
        "report_title": "本周业务数据报告",
        "date_range": "2025-10-15 至 2025-10-19",
        "total_users": "12,345",
        "new_users": "1,234",
        "active_rate": "87.5",
        "table_rows": table_rows_html,
        "highlights": highlights_html,
        "generate_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

    # 4. 渲染模板
    renderer = TemplateRenderer(template_dir="../templates")
    html_content = renderer.render("report.html", context)

    print("\n[渲染的HTML预览]")
    print(html_content[:300] + "...")

    # 5. 入队发送
    queue = MailQueue("mailer.sqlite3")
    payload = {
        "subject": f"📊 {context['report_title']} - {context['date_range']}",
        "to": ["manager@example.com"],
        "cc": ["team@example.com"],
        "body_html": html_content,
        "body_text": f"本周报告已生成,请查看附件或访问邮件查看详情。"
    }

    queue_id = queue.enqueue(payload)
    print(f"\n[OK] 邮件已入队, ID: {queue_id}")


def example3_inline_template():
    """示例3: 不使用文件,直接用字符串模板"""

    print("\n" + "=" * 60)
    print("示例3: 使用内联HTML模板")
    print("=" * 60)

    # 1. 定义内联模板
    template_string = """
    <html>
    <body style="font-family: Arial, sans-serif; padding: 20px;">
        <h2 style="color: #333;">订单确认</h2>
        <p>尊敬的 <strong>{{customer_name}}</strong>,</p>

        <p>您的订单已确认!</p>

        <table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
            <tr style="background: #f0f0f0;">
                <th style="padding: 10px; text-align: left;">商品</th>
                <th style="padding: 10px; text-align: right;">数量</th>
                <th style="padding: 10px; text-align: right;">单价</th>
            </tr>
            <tr>
                <td style="padding: 10px;">{{product_name}}</td>
                <td style="padding: 10px; text-align: right;">{{quantity}}</td>
                <td style="padding: 10px; text-align: right;">{{price}}</td>
            </tr>
        </table>

        <p><strong>总计: {{total}}</strong></p>

        <p>订单号: {{order_id}}</p>
        <p>预计送达: {{delivery_date}}</p>

        <hr>
        <p style="color: #999; font-size: 12px;">
            如有疑问,请联系客服: support@example.com
        </p>
    </body>
    </html>
    """

    # 2. 准备变量
    context = {
        "customer_name": "李四",
        "product_name": "Python编程书籍",
        "quantity": "2",
        "price": "¥89.00",
        "total": "¥178.00",
        "order_id": "ORD-20251021-001",
        "delivery_date": "2025-10-25"
    }

    # 3. 渲染
    renderer = TemplateRenderer()
    html_content = renderer.render_from_string(template_string, context)

    print("\n[渲染的HTML预览]")
    print(html_content[:300] + "...")

    # 4. 入队
    queue = MailQueue("mailer.sqlite3")
    payload = {
        "subject": f"订单确认 - {context['order_id']}",
        "to": ["customer@example.com"],
        "body_html": html_content,
        "body_text": f"订单 {context['order_id']} 已确认,总计 {context['total']}"
    }

    queue_id = queue.enqueue(payload)
    print(f"\n[OK] 邮件已入队, ID: {queue_id}")


def example4_batch_send():
    """示例4: 批量发送个性化邮件"""

    print("\n" + "=" * 60)
    print("示例4: 批量发送个性化邮件")
    print("=" * 60)

    # 简单的通知模板
    template = """
    <html>
    <body style="font-family: Arial, sans-serif;">
        <h2>Hi {{name}},</h2>
        <p>您的账号有 <strong>{{unread_count}}</strong> 条未读消息。</p>
        <p><a href="{{inbox_url}}" style="color: #007bff;">立即查看</a></p>
    </body>
    </html>
    """

    # 用户列表
    users = [
        {"name": "张三", "email": "zhang@example.com", "unread": 5},
        {"name": "李四", "email": "li@example.com", "unread": 12},
        {"name": "王五", "email": "wang@example.com", "unread": 3},
    ]

    renderer = TemplateRenderer()
    queue = MailQueue("mailer.sqlite3")

    for user in users:
        # 为每个用户渲染个性化内容
        context = {
            "name": user["name"],
            "unread_count": user["unread"],
            "inbox_url": f"https://example.com/inbox?user={user['email']}"
        }

        html_content = renderer.render_from_string(template, context)

        payload = {
            "subject": f"您有 {user['unread']} 条未读消息",
            "to": [user["email"]],
            "body_html": html_content,
            "body_text": f"Hi {user['name']}, 您有 {user['unread']} 条未读消息"
        }

        queue_id = queue.enqueue(payload)
        print(f"[OK] 用户 {user['name']} 邮件已入队, ID: {queue_id}")


if __name__ == "__main__":
    print("\n" + "=" * 60)
    print("HTML模板邮件发送示例")
    print("=" * 60)

    # 运行所有示例
    example1_simple_template()
    example2_complex_report()
    example3_inline_template()
    example4_batch_send()

    print("\n" + "=" * 60)
    print("所有示例执行完成!")
    print("=" * 60)
    print("\n提示: 使用 'uv run report-mailer send' 发送队列中的邮件")
